﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using Manoli.Utils.CSharpFormat;

namespace Ogdi.InteractiveSdk.WebForms
{
    /// <summary>
    /// Template-driven sample code generator.
    /// </summary>
    public class SampleCodeGenerator
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public SampleCodeGenerator()
        {
        }

        /// <summary>
        /// Initializing constructor.
        /// </summary>
        /// <param name="templateFilespec">Path/filename for template file.</param>
        /// <remarks>
        /// The template file is a text file that contains composite formatting specifications
        /// compatible with String.Format(). The first parameter {0} is the base URI for the
        /// container and authority. The second parameter {1} is the query.
        /// </remarks>
        public SampleCodeGenerator(string templateFilespec)
        {
            //  Read template
            StreamReader codeReader = new StreamReader(HttpContext.Current.Server.MapPath(templateFilespec));
            Template = codeReader.ReadToEnd();
            codeReader.Dispose();
        }


        /// <summary>
        /// Generate code using the current template.
        /// </summary>
        /// <param name="baseUri">Base URI for container and authority.</param>
        /// <param name="tableName">Table name.</param>
        /// <param name="query">Query</param>
        /// <returns>Sample code.</returns>
        public string GenerateCSharp(string baseUri, string tableName, string query)
        {
            string uri = baseUri + "/" + tableName;
            Template = Template.Replace("{0}", uri);
            Template = Template.Replace("{1}", query);

            var csharpFormat = new CSharpFormat();
            csharpFormat.Alternate = true;
            csharpFormat.EmbedStyleSheet = false;
            csharpFormat.LineNumbers = false;

            return csharpFormat.FormatCode(Template);
        }

        public string GenerateHtml(string baseUri, string query)
        {
            Template = Template.Replace("{0}", baseUri);
            Template = Template.Replace("{1}", query);
            Template = Template.Replace("{2}", query.Replace("_KML", string.Empty));

            var htmlFormat = new HtmlFormat();
            htmlFormat.Alternate = true;
            htmlFormat.EmbedStyleSheet = false;
            htmlFormat.LineNumbers = false;

            return htmlFormat.FormatCode(Template);
        }

        /// <summary>
        /// Code template.
        /// </summary>
        public string Template { get; set; }
    }
}
